package com.fitns.user.controller.user;

import com.fitns.user.conf.ZhhwResp;
import com.fitns.user.dto.user.PrivilegeVO;
import com.fitns.user.dto.user.RoleVO;
import com.fitns.user.dto.user.UserVO;
import com.fitns.user.model.user.Url;
import com.fitns.user.service.user.PrivilegeService;
import com.fitns.user.utils.ResultData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.fitns.user.model.user.Privilege;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RequestMapping("/privilege")
@RestController
@Api(description = "权限管理")
public class PrivilegeController {


    @Autowired
    private PrivilegeService privilegeService;

    @ApiOperation("插入所有URL到数据库")
    @PostMapping("/url")
    public ZhhwResp<List<Url>> getUrlMapping(HttpServletRequest request) {
        WebApplicationContext wc = WebApplicationContextUtils
                .getRequiredWebApplicationContext(request.getSession().getServletContext());
        RequestMappingHandlerMapping rmhp = wc.getBean(RequestMappingHandlerMapping.class);
        Map<RequestMappingInfo, HandlerMethod> map = rmhp.getHandlerMethods();
        List<Url> list = privilegeService.refreshUrls(map, request.getContextPath());
        return ZhhwResp.createSuccess(list);

    }

    @PutMapping("/refresh")
    @ApiOperation("刷新可以访问url的角色")
    public void refresh(){
        privilegeService.initUrlCodeRoleIdMapping();
    }


    @GetMapping("/getCurrentUserPrivilege")
    @ApiOperation("查找当前登录用户拥有的权限")
    public ZhhwResp getCurrentUserPrivilege(){
        List<Privilege> privileges=privilegeService.getCurrentUserPrivilege();
        return ZhhwResp.createSuccess(privileges);
    }

    @GetMapping("findPrivilegeByRole")
    @ApiOperation("查找指定角色拥有的权限")
    public ZhhwResp findPrivilegeByRole(RoleVO roleVO){
        List<Privilege> privileges=privilegeService.findPrivilegeByUser(roleVO);
        return ZhhwResp.createSuccess(privileges);
    }

    @PostMapping("/add")
    @ApiOperation("添加权限")
    public ZhhwResp add(@RequestBody PrivilegeVO privilegeVO){
        PrivilegeVO privilege= privilegeService.add(privilegeVO);
        return ZhhwResp.createSuccess(privilege);
    }
}
